import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { FaThumbsUp, FaReply, FaTrash } from 'react-icons/fa';
import Navbar from '../../components/Navbar/Navbar';
import './DownloadPage.css';

const DownloadPage = () => {
    const navigate = useNavigate();
    const location = useLocation();

    const [downloadStatus, setDownloadStatus] = useState(null);
    const [downloadProgress, setDownloadProgress] = useState(0);
    const [errorMessage, setErrorMessage] = useState('');
    const [torrentInfo, setTorrentInfo] = useState(null);
    const [loading, setLoading] = useState(true);
    const [coverImageUrl, setCoverImageUrl] = useState(null);
    const [comments, setComments] = useState([]);
    const [newComment, setNewComment] = useState('');
    const [replyingTo, setReplyingTo] = useState(null);
    const [replyContent, setReplyContent] = useState('');
    const [isAnonymous, setIsAnonymous] = useState(false);
    const [isReplyAnonymous, setIsReplyAnonymous] = useState(false);
    const [relatedTorrents, setRelatedTorrents] = useState([]);
    const [loadingRelated, setLoadingRelated] = useState(false);

    const queryParams = new URLSearchParams(location.search);
    const torrent_id = queryParams.get('torrent_id');
    const user_id = localStorage.getItem('userId');

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (!token || !user_id) {
            navigate('/login', { state: { from: location.pathname } });
            return;
        }
    }, [navigate, location.pathname, user_id]);

    const fetchTorrentDetails = async () => {
        try {
            const response = await fetch(`/torrent/getTorrentDetails/${torrent_id}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                throw new Error('获取种子详情失败');
            }

            const data = await response.json();

            if (data.result) {
                setTorrentInfo(data.rows);
                fetchCoverImage(torrent_id);
                fetchComments();
                fetchRelatedTorrents(torrent_id);
            } else {
                setErrorMessage(data.msg || '种子未找到');
            }
        } catch (error) {
            console.error('获取种子详情出错:', error);
            setErrorMessage('获取种子详情失败');
        } finally {
            setLoading(false);
        }
    };

    const fetchRelatedTorrents = async (torrentId) => {
        setLoadingRelated(true);
        try {
            const response = await fetch(`/torrent/recommend?torrentId=${torrentId}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                throw new Error('获取相关资源失败');
            }

            const data = await response.json();
            if (data.code === 0) {
                setRelatedTorrents(data.rows);
            } else {
                throw new Error(data.msg || '获取相关资源失败');
            }
        } catch (error) {
            console.error('获取相关资源出错:', error);
        } finally {
            setLoadingRelated(false);
        }
    };

    const renderRelatedTorrents = () => {
        if (loadingRelated) {
            return <div className="loading-message">加载相关资源中...</div>;
        }

        if (relatedTorrents.length === 0) {
            return <div className="no-related">暂无相关资源</div>;
        }

        return relatedTorrents.map((torrent) => (
            <div
                key={torrent.torrentId}
                className="related-item"
                onClick={() => navigate(`/download?torrent_id=${torrent.torrentId}`)}
            >
                {torrent.coverImage ? (
                    <img
                        src={`data:image/jpeg;base64,${torrent.coverImage}`}
                        alt={torrent.title}
                        className="related-thumbnail"
                        onError={(e) => {
                            e.target.onerror = null;
                            e.target.src = '';
                        }}
                    />
                ) : (
                    <div className="related-thumbnail placeholder">无封面</div>
                )}

                <div  className="related-item">
                    <h4 className="related-title">{torrent.title}</h4>

                </div>
                {/*{torrent.isPromo && <span className="promo-tag">推广</span>}*/}
            </div>
        ));
    };

    const fetchCoverImage = async (torrentId) => {
        try {
            const response = await fetch(`/torrent/getCoverImage?torrentId=${torrentId}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            console.log(response)
            if (response.ok) {
                const blob = await response.blob();
                const imageUrl = URL.createObjectURL(blob);
                setCoverImageUrl(imageUrl);
            } else {
                console.log('未找到封面图片或获取封面图片出错');
                setCoverImageUrl(null);
            }
        } catch (error) {
            console.error('获取封面图片出错:', error);
            setCoverImageUrl(null);
        }
    };

    const fetchComments = async () => {
        try {
            const response = await fetch(`/comments/listByTorrentId?torrentId=${torrent_id}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            if (response.ok) {
                const data = await response.json();
                setComments(data);
            }
        } catch (error) {
            console.error('获取评论列表出错:', error);
        }
    };

    useEffect(() => {
        if (torrent_id) {
            fetchTorrentDetails();
        } else {
            setErrorMessage('缺少种子ID参数');
            setLoading(false);
        }
    }, [torrent_id]);

    const handleBack = () => {
        navigate(-1);
    };

    const addToDownloadCount = async () => {
        try {
            const response = await fetch('/user/addToDownloadCount', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: new URLSearchParams({
                    userId: localStorage.getItem('userId'),  // 确保是字符串，URLSearchParams会自动处理
                    torrentId: torrent_id  // 同上
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                console.error('更新用户数据失败:', errorData.msg);
            }
        } catch (error) {
            console.error('更新用户数据出错:', error);
        }
    };

    const getInfoHash = async () => {
        try {
            const response = await fetch(`/torrent/getInfoHash?torrentId=${torrent_id}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                // body: JSON.stringify({
                //     userId: parseInt(localStorage.getItem('userId')),
                //
                // })
            });

            if (response.ok) {
                const errorData = await response.json();
                if (errorData.msg) {

                    try {
                        const response_infoHash = await fetch(`/torrent/announce?info_hash=${errorData.msg}&user_id=${parseInt(localStorage.getItem('userId'))}`, {
                            headers: {
                                'Authorization': `Bearer ${localStorage.getItem('token')}`
                            }
                        });
                        if (response_infoHash.ok) {
                            await addToDownloadCount();
                        }
                    } catch (error) {
                        console.error('获取评论列表出错:', error);
                    }
                }
                console.error('更新用户数据失败:', errorData.msg);
            }
        } catch (error) {
            console.error('更新用户数据出错:', error);
        }
    };


    const handleDownload = async () => {
        if (!torrent_id || !user_id) {
            setErrorMessage('缺少必要的参数');
            return;
        }

        setDownloadStatus('pending');
        setErrorMessage('');

        try {
            const response = await fetch(`/download/getfile?user_id=${user_id}&torrent_id=${torrent_id}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '下载失败');
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = torrentInfo ? `${torrentInfo.title}.torrent` : `torrent_${torrent_id}.torrent`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            await getInfoHash();

            setDownloadStatus('completed');
            setDownloadProgress(100);

        } catch (error) {
            console.error('下载出错:', error);
            setDownloadStatus('failed');
            setErrorMessage(error.message || '下载失败，请检查网络设置');
        }
    };

    const handleSubmitComment = async () => {
        if (!newComment.trim()) {
            alert('评论内容不能为空');
            return;
        }

        try {
            const response = await fetch('/comments/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({
                    torrentId: parseInt(torrent_id),
                    userId: parseInt(user_id),
                    content: newComment,
                    isAnonymous: isAnonymous ? "1" : "0"
                })
            });

            const contentType = response.headers.get('content-type');
            let data;

            if (contentType && contentType.includes('application/json')) {
                data = await response.json();
            } else {
                const text = await response.text();
                if (response.ok) {
                    setNewComment('');
                    setIsAnonymous(false);
                    fetchComments();
                    alert(text || '评论提交成功！');
                    return;
                } else {
                    throw new Error(text || '评论提交失败');
                }
            }

            if (!response.ok) {
                throw new Error(data.msg || '评论提交失败');
            }

            if (data.result) {
                setNewComment('');
                setIsAnonymous(false);
                fetchComments();
                alert('评论提交成功！');
            } else {
                throw new Error(data.msg || '评论提交失败');
            }
        } catch (error) {
            console.error('提交评论出错:', error);
            alert(`评论提交失败: ${error.message}`);
        }
    };

    const handleReply = async (commentId) => {
        if (!replyContent.trim()) {
            alert('回复内容不能为空');
            return;
        }

        try {
            const response = await fetch('/comments/reply', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({
                    torrentId: parseInt(torrent_id),
                    userId: parseInt(user_id),
                    comCommentId: parseInt(commentId),
                    content: replyContent,
                    isAnonymous: isReplyAnonymous ? "1" : "0"
                })
            });

            const responseText = await response.text();

            try {
                const data = JSON.parse(responseText);

                if (!response.ok) {
                    throw new Error(data.msg || '回复提交失败');
                }

                setReplyContent('');
                setReplyingTo(null);
                setIsReplyAnonymous(false);

                if (data.reply) {
                    setComments(prevComments =>
                        prevComments.map(comment =>
                            comment.commentId === commentId
                                ? {
                                    ...comment,
                                    replies: [...(comment.replies || []), data.reply]
                                }
                                : comment
                        )
                    );
                } else {
                    fetchComments();
                }

                alert(data.msg || '回复提交成功！');
            } catch (jsonError) {
                if (response.ok) {
                    setReplyContent('');
                    setReplyingTo(null);
                    setIsReplyAnonymous(false);
                    fetchComments();
                    alert(responseText || '回复提交成功！');
                } else {
                    throw new Error(responseText || '回复提交失败');
                }
            }
        } catch (error) {
            console.error('回复评论出错:', error);
            alert(`回复提交失败: ${error.message}`);
        }
    };

    const handleLikeComment = async (commentId) => {
        try {
            const response = await fetch(`/comments/like?commentId=${commentId}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.ok) {
                setComments(prevComments =>
                    prevComments.map(comment =>
                        comment.commentId === commentId
                            ? {
                                ...comment,
                                likesCount: comment.likesCount + 1,
                                isLiked: true
                            }
                            : comment
                    )
                );
            } else {
                const errorData = await response.json();
                alert(errorData.msg || '点赞失败');
            }
        } catch (error) {
            console.error('点赞评论出错:', error);
            alert('点赞失败，请重试');
        }
    };

    const handleUnlikeComment = async (commentId) => {
        try {
            const response = await fetch(`/comments/unlike?commentId=${commentId}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.ok) {
                setComments(prevComments =>
                    prevComments.map(comment =>
                        comment.commentId === commentId
                            ? {
                                ...comment,
                                likesCount: comment.likesCount - 1,
                                isLiked: false
                            }
                            : comment
                    )
                );
            } else {
                const errorData = await response.json();
                alert(errorData.msg || '取消点赞失败');
            }
        } catch (error) {
            console.error('取消点赞评论出错:', error);
            alert('取消点赞失败，请重试');
        }
    };

    const handleDeleteComment = async (commentId) => {
        if (window.confirm('确定要删除这条评论吗？')) {
            try {
                const response = await fetch(`/comments/delete?commentId=${commentId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (response.ok) {
                    fetchComments();
                    alert('评论删除成功！');
                } else {
                    const errorData = await response.json();
                    alert(errorData.msg || '删除失败');
                }
            } catch (error) {
                console.error('删除评论出错:', error);
                alert('删除失败，请重试');
            }
        }
    };

    useEffect(() => {
        if (downloadStatus === 'pending') {
            const interval = setInterval(() => {
                setDownloadProgress(prev => {
                    const newProgress = prev + 10;
                    if (newProgress >= 90) {
                        clearInterval(interval);
                        return 90;
                    }
                    return newProgress;
                });
            }, 500);

            return () => clearInterval(interval);
        }
    }, [downloadStatus]);


    const renderComments = (comments) => {
        return comments.map((comment) => (
          <div key={comment.commentId} className="comment-item">
            {/* 内容区域（左对齐） */}
            <div className="comment-content-section">
              <div className="comment-header">
                <span className="comment-author">
                  {comment.isAnonymous ? '匿名用户' : `用户${comment.userName}`}
                </span>
                <span className="comment-time">
                  {new Date(comment.commentTime).toLocaleString()}
                </span>
              </div>
              <div className="comment-content">{comment.content}</div>
            </div>

            {/* 操作按钮区域（右对齐） */}
            <div className="comment-actions">
              <button
                className={`action-button like-button ${comment.isLiked ? 'liked' : ''}`}
                onClick={() => comment.isLiked
                  ? handleUnlikeComment(comment.commentId)
                  : handleLikeComment(comment.commentId)
                }
              >
                <FaThumbsUp className="icon-like" />
                {comment.isLiked ? '已赞' : '赞'} ({comment.likesCount})
              </button>
              <button
                className="action-button reply-button"
                onClick={() => setReplyingTo(replyingTo === comment.commentId ? null : comment.commentId)}
              >
                <FaReply className="icon-reply" />
                回复
              </button>

               {/* 修复的主评论删除按钮 */}
                {(String(comment.userId) === localStorage.getItem('userId') || localStorage.getItem('role') === 'admin') && (
              <button
                className="action-button delete-button"
                onClick={() => handleDeleteComment(comment.commentId)}
              >
                <FaTrash className="icon-delete" />
                删除
              </button>
                )}
            </div>

            {replyingTo === comment.commentId && (
              <div className="reply-input">
                <textarea
                  placeholder="写下你的回复..."
                  value={replyContent}
                  onChange={(e) => setReplyContent(e.target.value)}
                />
                <div className="anonymous-checkbox">
                  <label>
                    <input
                      type="checkbox"
                      checked={isReplyAnonymous}
                      onChange={() => setIsReplyAnonymous(!isReplyAnonymous)}
                    />
                    匿名回复
                  </label>
                </div>
                <div className="reply-actions">
                  <button
                    className="submit-reply"
                    onClick={() => handleReply(comment.commentId)}
                  >
                    提交回复
                  </button>
                  <button
                    className="cancel-reply"
                    onClick={() => setReplyingTo(null)}
                  >
                    取消
                  </button>
                </div>
              </div>
            )}

            {comment.replies && comment.replies.length > 0 && (
              <div className="replies-container">
                {comment.replies.map((reply) => (
                  <div key={reply.commentId} className="reply-item">
                    <div className="comment-header">
                      <span className="comment-author">
                        {reply.isAnonymous ? '匿名用户' : `用户${reply.userName}`}
                      </span>
                      <span className="comment-time">
                        {new Date(reply.commentTime).toLocaleString()}
                      </span>
                    </div>
                    <div className="comment-content">{reply.content}</div>

                {/* 修复的回复删除按钮 */}
                {(String(reply.userId) === localStorage.getItem('userId') || localStorage.getItem('role') === 'admin') && (
                  <button
                    className="action-button delete-button"
                    onClick={() => handleDeleteComment(reply.commentId)}
                >
                    <FaTrash className="icon-delete" />
                  删除
                  </button>
              )}


                  </div>
                ))}
              </div>
            )}
          </div>
        ));
      };

    if (loading) {
        return (
            <div className="download-page">
                <Navbar />
                <div className="content-container">
                    <div className="loading-message">加载中...</div>
                </div>
            </div>
        );
    }

    if (errorMessage && !torrentInfo) {
        return (
            <div className="download-page">
                <Navbar />
                <div className="content-container">
                    <button className="back-button" onClick={handleBack}>返回</button>
                    <div className="error-message">{errorMessage}</div>
                </div>
            </div>
        );
    }

    if (!torrentInfo) {
        return (
            <div className="download-page">
                <Navbar />
                <div className="content-container">
                    <button className="back-button" onClick={handleBack}>返回</button>
                    <div className="error-message">无法获取种子信息</div>
                </div>
            </div>
        );
    }

    return (
        <div className="download-page">
            <Navbar />

            <div className="content-container">
                <button className="back-button" onClick={handleBack}>返回</button>

                <div className="torrent-grid">
                    <div className="torrent-details">
                        <div className="torrent-cover-container">
                            {coverImageUrl ? (
                                <img
                                    src={coverImageUrl}
                                    alt={torrentInfo.title}
                                    className="cover-image"
                                    onError={(e) => {
                                        e.target.onerror = null;
                                        e.target.src = '';
                                        setCoverImageUrl(null);
                                    }}
                                />
                            ) : (
                                <div className="cover-placeholder">暂无封面</div>
                            )}
                        </div>

                        <div className="comments-section">
                            <h3>评论 ({comments.length})</h3>
                            <div className="comment-input">
                                <textarea
                                    placeholder="写下你的评论..."
                                    value={newComment}
                                    onChange={(e) => setNewComment(e.target.value)}
                                ></textarea>
                            <div className="comment-actions">
                                <div className="anonymous-checkbox">
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={isAnonymous}
                                            onChange={() => setIsAnonymous(!isAnonymous)}
                                        />
                                        匿名评论
                                    </label>
                                </div>

                                <button
                                    className="submit-comment"
                                    onClick={handleSubmitComment}
                                >
                                    发表评论
                                </button>
                            </div>
                            </div>
                            <div className="comments-list">
                                {renderComments(comments)}
                            </div>
                        </div>

                    </div>



                    <div className="torrent-sidebar">
                        <div className="torrent-info-card">
                            <h1 className="torrent-title">{torrentInfo.title}</h1>
                            <p className="torrent-description">
                                {torrentInfo.description}
                            </p>

                            <div className="torrent-meta">
                                <div className="meta-item">
                                    <span className="meta-label">分类:</span>
                                    <span className="meta-value">{torrentInfo.category}</span>
                                </div>
                                <div className="meta-item">
                                    <span className="meta-label">标签:</span>
                                    <span className="meta-value">{torrentInfo.tags}</span>
                                </div>
                                <div className="meta-item">
                                    <span className="meta-label">上传时间:</span>
                                    <span className="meta-value">
                                        {new Date(torrentInfo.uploadTime).toLocaleString()}
                                    </span>
                                </div>
                                <div className="meta-item">
                                    <span className="meta-label">上传者:</span>
                                    <span className="meta-value">用户: {torrentInfo.userName}</span>
                                </div>
                            </div>

                            <div className="download-section">
                                <h3>种子下载</h3>
                                <div className="download-actions">
                                    <button
                                        className="download-button"
                                        onClick={handleDownload}
                                        disabled={downloadStatus === 'pending' || downloadStatus === 'in_progress'}
                                    >
                                        {downloadStatus === 'completed' ? '下载完成' :
                                            downloadStatus === 'pending' || downloadStatus === 'in_progress' ? '下载中...' : '开始下载'}
                                    </button>
                                </div>

                                {downloadStatus && (
                                    <div className="download-progress">
                                        <div
                                            className="progress-bar"
                                            style={{width: `${downloadProgress}%`}}
                                        ></div>
                                        <span>{downloadProgress}%</span>
                                    </div>
                                )}

                                {errorMessage && (
                                    <div className="error-message">
                                        {errorMessage}
                                    </div>
                                )}
                            </div>
                        </div>


                        <div className="related-torrents">
                            <h3>相关资源</h3>
                            <div className="related-list">
                                {renderRelatedTorrents()}
                            </div>
                        </div>


                    </div>
                </div>
            </div>
        </div>
    );
};

export default DownloadPage;
